import os

from core.twisteeng import TwitterClient
from PyQt4 import QtCore, QtGui, QtWebKit
from PyQt4.uic import loadUi
from utils import html

from config.config import TweestingConfig
import threading
import time

class Updater(QtCore.QThread):

    def __init__(self, parent=None):
        QtCore.QThread.__init__(self, parent)
        self.parent = parent

    def run(self):
        while 1:
            self.parent.request_for_new_tweets()
            self.emit(QtCore.SIGNAL("new_tweets()"))
            time.sleep(TweestingConfig.UPDATE_INTERVAL)

    def __del__(self):
        self.wait()

class FrmMain(QtGui.QMainWindow):

    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.twitterClient = TwitterClient()

        self.ui = loadUi(os.path.join(os.getcwd(), "gui/main.ui"))
        self.connect(self.ui.bt_post, QtCore.SIGNAL("clicked()"), self.btpost_click)
        self.connect(self.ui.tb_tweet, QtCore.SIGNAL("keyPressEvent(QKeyEvent)"), self.check_lenght)

        self.thread = Updater(self)
        self.connect(self.thread, QtCore.SIGNAL("new_tweets()"), self.update_tweets)
        self.thread.start()

    def btpost_click(self):
        self.post_tweet()

    def btrefresh_click(self):
        self.update_tweets()

    def post_tweet(self):
        tweet = self.ui.tb_tweet.toPlainText()
        try:
            self.twitterClient.post(tweet)
            self.request_for_new_tweets()
            self.update_tweets()
        except Exception, e:
            QtGui.QMessageBox.about(self, "Error", str(e))
        finally:
            self.ui.tb_tweet.setPlainText("")

    def check_lenght(self, event):
        print len(self.ui.tb_tweet.toPlainText())
        if len(self.ui.tb_tweet.toPlainText()) > 140:
            pass

    def request_for_new_tweets(self):
        self.tweets = self.twitterClient.get_friends_tweets()

    def update_tweets(self):
        self.render_page(self.tweets)

    def render_page(self, tweets):
        tweets = html.get_html({'tweets' : tweets})
        self.ui.web_tweets.setHtml(tweets)

    def show(self):
        """ Show the main windows """
        self.ui.show()


